﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DataObjects
{
    public static class GameMap
    {
        #region Attributes
        static private List<GameObject> theMap = new List<GameObject>();
        #endregion

        #region Basic Collection Methods
        static public void Add(GameObject piece)
        {
            if (!theMap.Contains(piece))
                theMap.Add(piece);
        }

        static public void Remove(GameObject piece)
        {
            if (theMap.Contains(piece))
                theMap.Remove(piece);
        }

        static public List<GameObject> GetPieces(bool ignoreDestroyed)
        {
            if (ignoreDestroyed)
                return theMap.Where(p => !p.IsDestroyed).ToList();
            else
                return theMap;
        }

        static public GameObject GetPiece(Guid id)
        {
            return theMap.FirstOrDefault(p => p.Id == id);
        }
        #endregion

        #region Public Methods
        static public int TeamsRemaining()
        {
            return theMap.Where(p => !p.IsDestroyed).GroupBy(p => p.Team).Count();
        }

        static public int DistanceBetween(GameObject piece1, GameObject piece2)
        {
            return Math.Abs(piece1.MapX - piece2.MapX) + Math.Abs(piece1.MapY - piece2.MapY);
        }

        static public GameObject ClosestTo(GameObject piece)
        {
            GameObject closest = null;
            
            foreach (GameObject obj in theMap.Where(p => !p.IsDestroyed))
            {
                if (closest == null)
                    closest = obj;

                if (DistanceBetween(obj, piece) < DistanceBetween(closest, piece))
                    closest = obj;
            }
            
            return closest;
        }

        static public GameObject ClosestEnemyTo(GameObject piece)
        {
            GameObject closest = null;

            foreach (GameObject obj in theMap.Where(p => p.Id != piece.Id && !p.IsDestroyed && p.Team != piece.Team))
            {
                if (closest == null)
                    closest = obj;
                else if (DistanceBetween(obj, piece) < DistanceBetween(closest, piece))
                    closest = obj;
            }

            return closest;
        }

        static public GameObject ClosestFriendTo(GameObject piece)
        {
            GameObject closest = null;

            foreach (GameObject obj in theMap.Where(p => !p.IsDestroyed && p.Team == piece.Team))
            {
                if (closest == null)
                    closest = obj;

                if (DistanceBetween(obj, piece) < DistanceBetween(closest, piece))
                    closest = obj;
            }

            return closest;
        }
        #endregion
    }
}
